<?php

namespace app\admin\controller;

use app\admin\model\BondLog;
use app\admin\model\Config;
use app\admin\model\HandlerModel;
use app\admin\model\VipModel;
use app\common\controller\Adminbase;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户管理
 */
class Member extends Adminbase
{

    /**
     * MemberModel模型对象
     * @var \app\admin\model\MemberModel
     */
    protected $modelClass = null;

    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new \app\admin\model\MemberModel;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Curd.php中对应的方法复制到当前控制器,然后进行修改
     */

    protected  $group = [1 => 'A类会员',2 => 'B类会员',  3 => 'C类会员'];


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $default_avatar = (new Config())->where(['id' => 26])->value('value');
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$page, $limit, $where, $sort, $order] = $this->buildTableParames();

            $list = $this->modelClass
                    ->withJoin('user','left')
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            //查询vip类型
            $vip = (new \app\admin\model\VipCard())->select()->toArray();
            $vip_name = array_column($vip, 'name','id');
            $vip_group = array_column($vip, 'vip_cate','id');
            $advise = (new HandlerModel())->column('tag','level');
            foreach ($list as &$row) {
                if ($row->user === null) {
                    $row->user = ''; // 将 null 设置为空字符串
                }
                if($row['vip_type']){
                    $row['vip_name'] = $this->group[$vip_group[$row['vip_type']]].'-'.$vip_name[$row['vip_type']];
                    $row['advise_name'] = $advise[$row['advise_level']];
                }
                if(!$row['avatar']){
                    $row['avatar'] = $default_avatar;
                }
            }

            $result = ["code" => 0, "count" => $list->total(), "data" => $list->items()];

            return json($result);
        }
        $vip = (new VipModel())->column('name','id');
        $advise = (new HandlerModel())->column('tag','level');
        $this->assign('vip',json_encode($vip));
        $this->assign('advise',json_encode($advise));
        return $this->fetch();
    }


    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param('id/d', 0);
        $row = $this->modelClass->get($id);
        if (!$row) {
            $this->error('记录未找到');
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error('你没有权限访问');
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    if($params['money'] > $row['bond'] || $params['money'] <= 0){
                        $this->error('输入金额不正确');
                    }
                    //执行扣除
                    $this->modelClass->where(['id' => $row['id']])->setDec('bond',$params['money']);
                    //添加记录
                    (new BondLog())->insert([
                       'member_id' => $row['id'],
                       'title' => '扣款'.$params['money'].'元',
                       'reason' => $params['reason'],
                       'money' => $params['money'],
                       'create_time' =>time(),
                    ]);
                    Db::commit();
                } catch (ValidateException | PDOException | Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('扣除成功');
            }
            $this->error('参数不能为空');
        }
        $this->view->assign("data", $row);
        return $this->fetch();
    }
}
